import { h, render, Component, VNode } from 'vue';
import { Popup, type PopupOptions } from './Popup'; // 假设 Popup 已用 TS 改造
import Cesium, { Viewer } from 'cesium';

interface PopupVueOptions {
  component?: Component | string; // Vue 组件
  position?: Cesium.Cartesian3; // 弹窗位置（世界坐标）
  popupCommonOption?: PopupOptions; // Popup 基础配置
  props?: Record<string, any>; // 传递给 Vue 组件的 props
}

export class PopupVue {
  private viewer: Viewer;
  private element: HTMLElement | null = null;
  private popup: Popup | null = null;

  constructor(viewer: Viewer, options: PopupVueOptions) {
    this.viewer = viewer;
    this.init(options);
  }

  private init(options: PopupVueOptions): void {
    const { component, position, popupCommonOption = {}, props = {} } = options;

    // 创建容器元素
    const div = document.createElement('div');
    div.style.position = 'absolute';
    div.className = 'popup';
    this.element = div;

    // 渲染 Vue 组件
    if (component) {
      const vnode: VNode = h(component, props);
      render(vnode, div);
    }

    // 添加到 Cesium 容器
    this.viewer.container.appendChild(div);

    // 初始化 Popup
    this.popup = new Popup(this.viewer, {
      ...popupCommonOption,
      element: div,
      position
    });
  }

  /**
   * 移除弹窗
   */
  remove(): void {
    if (this.element && this.viewer.container.contains(this.element)) {
      this.viewer.container.removeChild(this.element);
    }

    this.popup?.destroy();

    this.element = null;
    this.popup = null;
  }

  /**
   * 更新弹窗位置
   * @param position 新的世界坐标
   */
  setPosition(position: Cesium.Cartesian3): void {
    this.popup?.setPosition(position);
  }

  /**
   * 更新 Vue 组件 props
   * @param props 新的 props
   */
  updateProps(props: Record<string, any>): void {
    if (this.element && this.element.firstChild) {
      const vnode = h(this.element.firstChild as Component, props);
      render(vnode, this.element);
    }
  }
}
